package org.yxj.lib_storage;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * @author on 2024/4/28
 */
public class FileUtils {


    /**
     *
     * 将Uri 转成 File
     *
     * @param context
     * @param uri
     * @param callBack
     */
    public static void saveUriToFile(Context context , Uri uri, String saveFilePath, CallBack<File> callBack){
        try {
            AssetFileDescriptor descriptor = context.getContentResolver().openAssetFileDescriptor(uri, "r");
            Bitmap b = BitmapFactory.decodeFileDescriptor(descriptor.getFileDescriptor());
            File file = new File(saveFilePath);
            b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
            if (callBack!=null){
                callBack.success(file);
            }
            b.recycle();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            if (callBack!=null){
                callBack.error(-1,e.getMessage());
            }
        }
    }
}
